package yunjiao.javatutorials.guava.concurrent;

import com.google.common.util.concurrent.*;

import java.util.concurrent.Executors;

/**
 * 异常处理示例
 *
 * @author yangyunjiao
 */
public class ExceptionHandlingExample {
    public static void main(String[] args) {
        ListeningExecutorService executor =
                MoreExecutors.listeningDecorator(Executors.newFixedThreadPool(2));

        // 模拟会抛出异常的任务
        ListenableFuture<String> future = executor.submit(() -> {
            Thread.sleep(1000);
            if (Math.random() > 0.5) {
                throw new RuntimeException("模拟任务失败");
            }
            return "任务成功完成";
        });

        Futures.addCallback(future, new FutureCallback<String>() {
            @Override
            public void onSuccess(String result) {
                System.out.println("任务成功: " + result);
            }

            @Override
            public void onFailure(Throwable t) {
                System.err.println("任务失败，错误信息: " + t.getMessage());
                // 可以进行重试或其他错误处理逻辑
            }
        }, executor);

        // 等待任务完成
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        } finally {
            executor.shutdown();
        }
    }
}
